import style from './index.module.scss'
import HeaderView from "@/components/Header"
import { Form, Input, Button, Toast } from 'antd-mobile'
import { NavLink, useNavigate } from 'react-router-dom'
import { UserRegister } from '@/api/login'
import { register } from './type'

const Register = () => {
  const navigate = useNavigate()

  const validatePsw = ({getFieldValue}: any) => { // 验证两次密码输入是否一致
    return {
      validator: (_: any, value: string) => { // 此处的_下划线 个人理解的是当前对象
        if(!value || getFieldValue('password') === value){
          return Promise.resolve()
        }
        return Promise.reject(new Error('两次输入密码不一致, 请重新输入'))
      }
    }
  }

  // 提交表单
  const onFinish = async (values: register) => {
    const res = await UserRegister({name: values.name, email: values.email, password: values.password, password_confirmation: values.passwordConfirmation})

    try {
      if(res.status === 201) {
        Toast.show({icon: 'success', content: '注册成功', maskClickable: false, afterClose: () => {
          navigate('/login')
        }})   
      }
    } catch (error) {
      console.log(error)
    }
  }  

  return (
    <>
      {/* header信息 */}
      <HeaderView backIcon={false} title='注册中心' backPath=''></HeaderView>

      {/* 注册表单 */}
      <div className={style.box}>
        <Form onFinish={onFinish} layout='horizontal' footer={ 
           <>
            <NavLink to='/login' className={style.link}>已有账号,立即登陆</NavLink>
            <Button block type='submit' size='large' className={style.btn}>注册</Button>
           </>
        }>
            <Form.Item name='name' label='用户名' rules={[ { required: true, message: '用户名不能为空' }, { min: 3, max: 6, pattern: /^[a-zA-Z0-9]{3,6}$/, message: '用户名长度3-6位,由数字和字母组成' }]}>
               <Input placeholder='请输入用户名' />
            </Form.Item>

            <Form.Item name='password' label='密码' rules={[ { required: true, message: '密码不能为空' }, { min: 6, max: 10, pattern: /^[a-zA-Z0-9]{6,10}$/, message: '密码长度6-10位,由数字和字母组成'} ]}>
               <Input placeholder='请输入密码' type='password'/>
            </Form.Item>

            <Form.Item name='passwordConfirmation' label='确认密码' dependencies={['password']} validateTrigger="onBlur"  rules={[ { required: true, message: '密码不能为空' }, validatePsw]}>
                <Input placeholder='请确认密码' type='password'/>
            </Form.Item>

            <Form.Item name='email' label='邮箱' rules={[{ required: true, message: '邮箱不能为空' }]}>
                <Input placeholder='请输入邮箱' />
            </Form.Item>
        </Form>
      </div>
    </>
  )
}

export default Register